<?php

namespace app\api\controller;

use app\admin\model\Villagemessages;
use app\admin\model\Member;
use app\admin\model\Image;
use app\admin\model\Operatorjob;
use app\admin\model\Operator;
use app\admin\model\Organizationjob;

use app\common\BaseHelper;
use app\lib\Qiniu;
use think\Db;


class Message extends BaseController {

    //获取所有留言
    public function getAllMessage() {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;
        if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId不能为空');
        }
        $where = ['a.villageId'=>$param->villageId,'isDelete'=>2,'responderId'=>'0'];
        if (!empty($param->userId)) {  //查询某一用户下的留言列表
            $where['userId'] = $param->userId;
        }

        $total = Villagemessages::alias('a')->where($where)->count();
        //所有一级留言
        $list = Villagemessages::alias('a')->join('user b','a.userId=b.id')->field('a.*,b.nickName,b.avatarUrl,b.mobile,b.isMember,b.memberId')->where($where)->limit($start,$length)->order('a.createDate DESC')->select();
        if(empty($list)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '数据为空');
        }

        $memberList = Member::where('villageId',$param->villageId)->select();
        $memberMap = [];  //查出所有村民列表，避免循环查询，提高速度
        foreach ($memberList as $m) {
            $memberMap[$m['id']] = $m;
        }

        $operator = Operator::alias('a')->join('operatorjob c','a.id=c.operatorId')->join('organizationjob d','c.jobId=d.id')->field('a.*,d.name')->where(['d.villageId' => $param->villageId])->select();
        $operatorMap = [];  //查出所有职务列表
        foreach ($operator as $o) {
            $operatorMap[$o['memberId']] = $o['name'];
        }

        $id = [];
        foreach ($list as $k => $v) {
            if($v['isMember'] == 1) {  //本村村民
                $list[$k]['nickName'] = $memberMap[$v['memberId']]['name'];
                $list[$k]['avatarUrl'] = $memberMap[$v['memberId']]['avatar'];
                $list[$k]['mobile'] = $memberMap[$v['memberId']]['mobile'];
            }
            $v->image;
            $id[] = $v['id'];  //一级留言ID组，以便查找所有回复
        }
        //所有回复
        $replayList = Villagemessages::field('content,userId,responderId,createDate')->where('responderId','in',implode(',', $id))->where(['isDelete'=>2])->select();
        $replayMap = [];
        foreach ($replayList as $rk => $rv) {
            $rv['nickName'] = $memberMap[$rv['userId']]['name'];
            $rv['job'] = isset($operatorMap[$rv['userId']]) ? $operatorMap[$rv['userId']] : '';
            $replayMap[$rv['responderId']][] = $rv;
        }
        foreach ($list as $k => $v) {
            $list[$k]['replay'] = isset($replayMap[$v['id']]) ? $replayMap[$v['id']] : '';
        }
        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);

    }

    //删除留言
    public function delMessage() {
        $param = self::getHttpParam();
        if (empty($param->messageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'messageId不能为空');
        }
        $del = Villagemessages::where(['id'=>$param->messageId])->whereOr(['responderId'=>$param->messageId])->update(['isDelete'=>1]);
        if($del) {
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $del);
        } else {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除失败');
        }

    }

    //发布留言
    public function createMessage() {
        $param = self::getHttpParam();
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId不能为空');
        }
        if (empty($param->content)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'content不能为空');
        }
        if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId不能为空');
        }
        $id = BaseHelper::getUUID();

        Db::startTrans();
        if(isset($param->imageId) || $param->imageId) {
            $imageId = is_array($param->imageId) ? implode(',', $param->imageId) : $param->imageId;
            $update = Image::where('id','in',$imageId)->update(['relatedId'=>$id,'villageId'=>$param->villageId]);
        }
        $data = [
            'userId' => $param->userId,
            'content' => $param->content,
            'villageId' => $param->villageId,
            'id' => $id,
            'createDate' => time()
        ];
        $result = Villagemessages::create($data);
        if($result) {
            Db::commit();
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
        }

        // if ($result && $this->_upload_images($id, $param->villageId ,$msg)) {
        //     Db::commit();
        //     return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
        // }
        Db::rollback();
        return show(config('status.ERROR_STATUS'), self::NOT_DATA, $msg);
    }

    //上传单张图片
    public function uploadImg() {
        // $param = self::getHttpParam();
        // if (empty($param->villageId)) {
        //     return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId不能为空');
        // }
        $Qiniu = new Qiniu();
        $result = $Qiniu->postDoupload($_FILES['images']);
        if($result['status'] == 'fail') {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, $result['message']);
        }
        $data = [
            'id' => BaseHelper::getUUID(),
            'imgUrl' => 'http://img.1miaodao.cn/'.$result['key'],
            // 'villageId' => $param->villageId,
            'created' => time(),
            'relatedTable' => 'villagemessages'
        ];
        if(Image::insert($data)) {
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
        }
        return show(config('status.ERROR_STATUS'), self::NOT_DATA, '插入失败');
        
    }

    /**
     * 上传图片
     * @param string $id 留言ID
     * @param string $msg 错误提示语
     * @return boolean 是否上传成功
     */
    private function _upload_images($id, $villageId, &$msg) {
        
        if (!$_FILES['images']) {  // 如果没有图片直接返回
            return TRUE;
        }

        // 将 $_FILES 的多个文件类型格式化
        $files = $this->_format_files($_FILES['images']);
        // 检查图片是否合法
        if (!$this->_check_images($files, $msg)) {
            return FALSE;
        }

        $Qiniu = new Qiniu();
        foreach ($files as $file) {
            // 上传图片
            $result = $Qiniu->postDoupload($file);
            if($result['status'] == 'fail') {
                return $this->error($result['message']);
            }
            $data = [
                'id' => BaseHelper::getUUID(),
                'imgUrl' => 'http://img.1miaodao.cn/'.$result['key'],
                'villageId' => $villageId,
                'controller' => 'villagemessages',
                'created' => time(),
                'relatedId' => $id,
                'relatedTable' => 'villagemessages'
            ];
            Image::insert($data);
        }
        return TRUE;
    }

    /**
     * 将 $_FILES 的多个文件类型格式化
     * @param array $files $_FILES['xxx']
     * @return array 格式化后返回的新数组
     */
    private function _format_files($files) {
        $result = array();
        foreach ($files as $field => $value) {
            if (!is_array($value)) {
                continue;
            }
            foreach ($value as $key => $val) {
                $result[$key][$field] = $val;
            }
        }

        return $result;
    }

    /**
     * 允许最大上传图片数量
     * @var int 
     */
    private $_image_max_num = 9;

    /**
     * 允许最大上传图片大小
     * @var int 
     */
    private $_image_max_size = 3145728; // 3 * 1024 * 1024

    /**
     * 允许图片类型
     * @var array 
     */
    private $_image_allow_types = array('png', 'jpg', 'jpeg','gif');

    /**
     * 检查上传文件是否合法
     * @param array $files
     * @param string $msg 错误提示语
     * @return boolean TRUE:合法 or FALSE:不合法
     */
    private function _check_images($files, &$msg) {
        if ($this->_image_max_num < count($files)) {
            $msg = '图片数量过多';
            return FALSE;
        }

        foreach ($files as $file) {
            // 检查文件类型
            if (!in_array(strtolower($this->_get_file_ext($file['name'])), $this->_image_allow_types)) {
                $msg = '图片类型非法';
                return FALSE;
            }

            // 检查上传错误
            if (0 !== $file['error']) {
                $msg = '图片文件损坏';
                return FALSE;
            }
            
            // 检查文件大小
            if ($file['size'] >= $this->_image_max_size) {
                $msg = '图片文件过大';
                return FALSE;
            }
        }

        return TRUE;
    }

    /**
     * 获取文件后缀名
     * @param string $filename
     * @return string 后缀名
     */
    private function _get_file_ext($filename) {
        return substr(strrchr($filename, '.'), 1);
    }

}